<script setup lang="ts">
import { ref } from "vue";
import { provinceAndCityData } from "@/utils/chinaArea";
import {
  customer_import_one,
  customer_import_all,
  customer_schedule
} from "@/api/customer";
import {
  tags_list,
  tags_add
} from "@/api/tag";
import { message } from "@/utils/message";
import { reactive } from "vue";
import type { FormRules } from "element-plus";
import { UploadFilled, Eleme } from "@element-plus/icons-vue";
import Import from "~icons/pajamas/import";
import prompticon from "~icons/garden/alert-warning-fill-12";
import type { UploadProps } from "element-plus";
import ABProgress from "@/components/ABProgress/index.vue";
import Disclaimer from "./disclaimer.vue";

const emit = defineEmits(["onSearch", "onLabelChange"]);

const baseUrl = 'https://crm.wxbqq.com/crmback/public/index.php/'
// const baseUrl = '/api/'

const SingleFormRules = reactive(<FormRules>{
  company_name: [
    { required: true, message: "公司名称为必填项", trigger: "blur" }
  ],
  city: [
    { required: true, message: "所在地区为必选项", trigger: ["blur", "change"] }
  ],
  name: [{ required: true, message: "法人代表为必填项", trigger: "blur" }],
  phone: [
    { required: true, message: "联系电话为必填项", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的联系电话",
      trigger: "blur"
    }
  ],
  tags_id: [
    { required: true, message: "客户标签为必选项", trigger: ["blur", "change"] }
  ]
});

const BatchFormRules = reactive(<FormRules>{
  file: [{ required: true, message: "请上传导入文件", trigger: "blur" }],
  tags_id: [
    { required: true, message: "客户标签为必选项", trigger: ["blur", "change"] }
  ]
});

// 自导入弹窗
const drawer = ref(false);

const importType = ref(2);
const importTypeList = ref([
  {
    value: 2,
    label: "批量导入"
  },
  {
    value: 1,
    label: "单个导入"
  }
  
]);

const labelOptions = ref([]);
const labelName = ref()
const onLabelConfirm = () => {
  if (labelName.value) {
    tags_add({
      name: labelName.value,
      sort: 1,
      status: 1
    }).then(res => {
      if (res.code == 1000) {
        message('添加成功', { type: "success" });
        getLabelList()
        emit("onLabelChange"); // 刷新列表tag
        labelName.value = ''
      } else {
        message(res.msg, { type: "error" });
      }
    });
  } else {
    message("请输入标签名称", { type: "warning" });
  }
}

// 获取客户标签
function getLabelList() {
  tags_list({
    page: 1,
    pagesize: 999,
    status: 1
  }).then(res => {
    labelOptions.value = res.data
  })
}

const SingleRuleFormRef = ref();
const BatchRuleFormRef = ref();
const upload = ref();
const formInline = ref();

// 免责声明弹窗
const disclaimerRef = ref();

// 打开弹窗
function openDrawer(label) {
  formInline.value = {
    company_name: "",
    city: [],
    name: "",
    phone: "",
    file: "",
    tags_id: ""
  };
  labelOptions.value = label;
  drawer.value = true;
}

// 取消
function closeClick() {
  if (importType.value == 2) BatchRuleFormRef.value.resetFields();
  else SingleRuleFormRef.value.resetFields();
  drawer.value = false;
}

const dowmloadfile = (url) => {
  window.open(url);
};

const handleSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  if (response.code == 1000) {
    formInline.value.file = response.data;
  } else {
    message(response.msg, { type: "error" });
  }
};

const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  const isXLSX = rawFile.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  if (!isXLSX) {
    message("文件格式不正确！", { type: "error" });
    return false;
  }
  return true;
};

// 确定
function confirmClick() {
  if (importType.value == 2) {
    BatchRuleFormRef.value.validate(valid => {
      if (valid) {
        // 打开免责声明弹窗
        disclaimerRef.value.openDialog();
      }
    });
    return false;
  }
  SingleRuleFormRef.value.validate(valid => {
    if (valid) {
      // 打开免责声明弹窗
      disclaimerRef.value.openDialog();
    }
  });
}

// 已阅读同意免责声明
function disclaimerRead() {
  if (importType.value == 2) {
    batchImport();
  } else {
    singleImport();
  }
}

const isImportLoading = ref(false);
const progress = ref(0);
let queryInterval = null;
// 执行批量导入
function batchImport() {
  let form = JSON.parse(JSON.stringify(formInline.value));
  customer_import_all({
    file: form.file,
    tags_id: form.tags_id
  }).then(res => {
    if (res.code == 1000) {
      isImportLoading.value = true;
      queryImport(res.data.logId);
      queryInterval = setInterval(() => {
        queryImport(res.data.logId);
      }, 1000);
    }
  });
}

// 导入轮询
function queryImport(id) {
  customer_schedule({ logId: id }).then(res => {
       let resData = res.data;
    if (resData.status === "doing" || resData.status === "going") {
      let numProgress = ((resData.num / resData.total_num) * 100).toFixed(0);
      progress.value = Number(numProgress);
    } else if(resData.status == "done") {
      progress.value = 100;
      clearInterval(queryInterval);
      queryInterval = null;

      setTimeout(() => {
        isImportLoading.value = false;
        message("执行完毕", { type: "success" });
        progress.value = 0;
        upload.value.clearFiles();
        BatchRuleFormRef.value.resetFields();
        drawer.value = false;
        emit("onSearch"); // 刷新表格数据
      }, 800);
    }
  }).catch(err => {
    clearInterval(queryInterval);
    queryInterval = null;

    setTimeout(() => {
      isImportLoading.value = false;
      message(err.msg, { type: "error" });
      progress.value = 0;
      upload.value.clearFiles();
      BatchRuleFormRef.value.resetFields();
      drawer.value = false;
      emit("onSearch"); // 刷新表格数据
    }, 800);
  });
}

// 执行单个导入
function singleImport() {
  let form = JSON.parse(JSON.stringify(formInline.value));
  customer_import_one({
    company_name: form.company_name,
    province: form.city[0],
    city: form.city[1],
    name: form.name,
    phone: form.phone,
    tags_id: form.tags_id
  }).then(res => {
    if (res.code == 1000) {
      isImportLoading.value = true;
      setTimeout(() => {
        progress.value = 50;
      }, 800);
      setTimeout(() => {
        progress.value = 100;
      }, 1600);
      setTimeout(() => {
        isImportLoading.value = false;
        message(`操作成功！`, { type: "success" });
        progress.value = 0;
        SingleRuleFormRef.value.resetFields();
        drawer.value = false;
        emit("onSearch"); // 刷新表格数据
      }, 2400);
    }
  });
}
defineExpose({ openDrawer });
</script>

<template>
  <div>
    <!-- <ABProgress
      v-model:show="showProgress"
      v-model:process="Process"
    ></ABProgress> -->
    <el-drawer
      v-model="drawer"
      size="460"
      title="自导入"
      direction="ltr"
      @handleClose="closeClick"
    >
      <div class="cardTab" style="margin-bottom: 20px">
        <el-radio-group v-model="importType" size="large">
          <el-radio-button
            v-for="(item, index) in importTypeList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-radio-group>
      </div>

      <!-- 单个导入 -->
      <div class="dialog" v-if="importType == 1">
        <el-form
          ref="SingleRuleFormRef"
          :rules="SingleFormRules"
          :model="formInline"
        >
          <el-form-item label="公司名称:" prop="company_name">
            <el-input
              v-model="formInline.company_name"
              clearable
              maxlength="50"
              placeholder="请输入公司名称"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="所在地区:" prop="city">
            <el-cascader
              class="w-[100%]!"
              v-model="formInline.city"
              placeholder="所在地区"
              :options="provinceAndCityData"
              :props="{ value: 'label' }"
              clearable
            />
          </el-form-item>
          <el-form-item label="法人代表:" prop="name">
            <el-input
              v-model="formInline.name"
              clearable
              maxlength="10"
              placeholder="请输入法人代表"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="联系电话:" prop="phone">
            <el-input
              v-model="formInline.phone"
              clearable
              maxlength="11"
              placeholder="请输入联系电话"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="客户标签:" prop="tags_id">
            <el-select
              v-model="formInline.tags_id"
              placeholder="请选择"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(item, index) in labelOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
              <template #footer>
                <div class="flex">
                  <el-input
                    v-model="labelName"
                    placeholder="输入新增项"
                    class="mr-2"
                  />
                  <el-button type="primary" @click="onLabelConfirm">
                    确认新增
                  </el-button>
                </div>
              </template>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <!-- 批量导入 -->
      <div class="dialog" v-if="importType == 2">
        <div
          class="template"
          @click="dowmloadfile('https://crm.wxbqq.com/crmback/public/file.xlsx')"
        >
          <p>下载模板：</p>
          <div>
            <IconifyIconOffline
              :icon="Import"
              style="color: #15bbbb; width: 15px; height: 15px"
            />
            <span>批量导入数据标准录入模板</span>
          </div>
        </div>

        <el-form
          ref="BatchRuleFormRef"
          :rules="BatchFormRules"
          :model="formInline"
          label-position="top"
        >
          <el-form-item label="导入文件:" prop="file">
            <div class="w-full">
              <el-upload
                ref="upload"
                drag
                :action="`${baseUrl}index/uploadLocal`"
                :limit="1"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">拖拽到这里或<em>点击上传</em></div>
              </el-upload>

              <div class="tip">
                <IconifyIconOffline
                  :icon="prompticon"
                  style="color: #999999; width: 16px; height: 16px"
                />
                <p>上传文件必须是xlsx格式，并且数据条数小于300,000行</p>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="客户标签:" prop="tags_id">
            <div class="w-full">
              <el-select
                v-model="formInline.tags_id"
                placeholder="请选择"
                class="w-full"
                clearable
              >
                <el-option
                  v-for="(item, index) in labelOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
                <template #footer>
                  <div class="flex">
                    <el-input
                      v-model="labelName"
                      placeholder="输入新增项"
                      class="mr-2"
                    />
                    <el-button type="primary" @click="onLabelConfirm">
                      确认新增
                    </el-button>
                  </div>
                </template>
              </el-select>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div style="flex: auto">
          <el-button @click="closeClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">确定</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 免责声明 -->
    <Disclaimer ref="disclaimerRef" @onRead="disclaimerRead"></Disclaimer>

    <!-- 批量导入loading -->
    <div class="importLoading" v-if="isImportLoading">
      <div class="loading spin"></div>
      <div class="progress">
        <div class="barInner" :style="{ width: `${progress}%` }">
          <div class="text">{{ progress }}%</div>
        </div>
      </div>
      <div class="importText">正在导入中，请稍等...</div>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-drawer__header) {
  margin-bottom: 0 !important;
}

.dialog {
  background-color: #f5f5f5;
  padding: 18px 18px 0;
  border-radius: 7px;
  overflow: hidden;
}

.template {
  p {
    font-size: 14px;
    color: #000;
  }
  div {
    display: flex;
    align-items: center;
    margin: 10px 0 20px;
    cursor: pointer;
    span {
      font-size: 14px;
      color: #15bbbb;
      margin-left: 10px;
    }
  }
}

.tip {
  display: flex;
  align-items: center;
  background-color: #f0f0f0;
  border: 1px solid #d9d9d9;
  padding: 3px 6px;
  line-height: 21px;
  margin-top: 8px;

  p {
    font-size: 12px;
    color: #999999;
    margin-left: 5px;
    font-weight: bold;
  }
}

.importLoading {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background-color: #6a7282;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;

  .loading {
    width: 9px;
    height: 9px;
    border-radius: 100%; /* 圆角 */
    box-shadow:
      0 -30px 0 3px #ffffff,
      /* 原0 -10px 0 1px × 3 */ 30px 0px #ffffff,
      /* 原10px × 3 */ 0 30px #ffffff,
      /* 原10px × 3 */ -30px 0 #ffffff,
      /* 原10px × 3 */ -21px -21px 0 1.5px #ffffff,
      /* 原-7px -7px 0 0.5px × 3 */ 21px -21px 0 4.5px #ffffff,
      /* 原7px -7px 0 1.5px × 3 */ 21px 21px #ffffff,
      /* 原7px × 3 */ -21px 21px #ffffff; /* 原7px × 3 */
  }

  .spin {
    animation: spin 1s steps(8) infinite;
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  .progress {
    width: 720px;
    height: 12px;
    display: flex;
    align-items: center;
    margin-top: 100px;
    background: #e5e5e5;
    border-radius: 10px;

    .barInner {
      height: 12px;
      background: var(--pure-theme-menu-active-before);
      border-radius: 10px;
      position: relative;
      transition: all 0.5s;

      .text {
        padding: 0 12px;
        font-size: 20px;
        color: #ffffff;
        background: var(--pure-theme-menu-active-before);
        border-radius: 20px;
        position: absolute;
        right: -40px;
        top: 50%;
        transform: translateY(-50%);
        text-align: center;
      }
    }
  }

  .importText {
    margin-top: 60px;
    font-size: 18px;
    color: #ffffff;
  }
}
</style>
